package com.rabbitMQ.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer_Topics {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.23.129"); // 设置连接 ip 默认 localhost
        factory.setPort(5672);  // 设置连接端口 默认 5672
        factory.setVirtualHost("/root"); // 虚拟机 我们这里使用 /root
        factory.setUsername("root");    // 拥有权限的用户
        factory.setPassword("root");    // 拥有权限的用户密码
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 交换机名称
        String exchangeName = "exchange_topic";
        // 队列名称
        String queue1Name = "topic_queue1";
        String queue2Name = "topic_queue2";
        // 创建交换机
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, true, false, false, null);
        // 创建队列
        channel.queueDeclare(queue1Name, false, false, false, null);
        channel.queueDeclare(queue2Name, false, false, false, null);
        // 绑定交换机和对垒
        channel.queueBind(queue1Name,exchangeName,"*.orange.*");
        channel.queueBind(queue2Name,exchangeName,"*.*.rabbite");
        channel.queueBind(queue2Name,exchangeName,"Lazy.#");
        // 发送消息 指定
        channel.basicPublish(exchangeName, "a.orange.b", null, ("Hello queues ==a.orange.b==").getBytes());
        channel.basicPublish(exchangeName, "a.b.rabbite", null, ("Hello queues ==a.b.rabbite==").getBytes());
        channel.basicPublish(exchangeName, "Lazy.aabb", null, ("Hello queues ==Lazy.aabb==").getBytes());
        // 未被绑定到指定通配符 消息将被丢弃
        channel.basicPublish(exchangeName, "未知的匹配模式", null, ("Hello queues ==未知的匹配模式==").getBytes());
        // 关闭资源
        channel.close();
        connection.close();
    }
}
